'use client'

import { useState, useEffect } from 'react'
import DashboardLayout from '@/components/layouts/DashboardLayout'
import { Card, Tag } from 'antd'
import { Home, Lightbulb, PlayCircle, Settings, Power, PowerOff } from 'lucide-react'
import { Device, SceneExecution } from '@/types/device'

export default function DashboardPage() {
  const [stats, setStats] = useState({
    deviceCount: 0,
    sceneCount: 0,
    activeSceneCount: 0,
    executionCount: 0
  })
  const [devices, setDevices] = useState<Device[]>([])
  const [recentExecutions, setRecentExecutions] = useState<SceneExecution[]>([])

  useEffect(() => {
    fetchStats()
    fetchDevices()
    fetchRecentExecutions()
  }, [])

  const fetchStats = async () => {
    try {
      // 获取设备总数
      const devicesRes = await fetch('/api/devices')
      const devices = await devicesRes.json()
      
      // 获取场景数据
      const scenesRes = await fetch('/api/scenes')
      const scenes = await scenesRes.json()
      
      setStats({
        deviceCount: Array.isArray(devices) ? devices.length : 0,
        sceneCount: Array.isArray(scenes) ? scenes.length : 0,
        activeSceneCount: Array.isArray(scenes) ? scenes.filter(scene => scene.isActive).length : 0,
        executionCount: 0 // 暂时设为 0，后续可以添加执行记录统计
      })
    } catch (error) {
      console.error('获取统计数据失败:', error)
    }
  }

  const fetchDevices = async () => {
    try {
      const res = await fetch('/api/devices')
      const data = await res.json()
      console.log('设备数据:', data)
      if (Array.isArray(data)) {
        setDevices(data)
      }
    } catch (error) {
      console.error('获取设备列表失败:', error)
    }
  }

  const fetchRecentExecutions = async () => {
    try {
      const res = await fetch('/api/scenes/executions')
      const data = await res.json()
      if (Array.isArray(data)) {
        setRecentExecutions(data)
      }
    } catch (error) {
      console.error('获取执行记录失败:', error)
    }
  }

  const cards = [
    {
      title: '设备总数',
      value: stats.deviceCount,
      icon: <Home className="w-6 h-6 text-blue-400" />,
      color: 'bg-blue-500/10'
    },
    {
      title: '场景总数',
      value: stats.sceneCount,
      icon: <Settings className="w-6 h-6 text-green-400" />,
      color: 'bg-green-500/10'
    },
    {
      title: '已启用场景',
      value: stats.activeSceneCount,
      icon: <PlayCircle className="w-6 h-6 text-yellow-400" />,
      color: 'bg-yellow-500/10'
    },
    {
      title: '场景执行次数',
      value: stats.executionCount,
      icon: <Lightbulb className="w-6 h-6 text-purple-400" />,
      color: 'bg-purple-500/10'
    }
  ]

  return (
    <DashboardLayout>
      <div className="space-y-8">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {cards.map((card, index) => (
            <div
              key={index}
              className={`p-6 rounded-lg ${card.color} border border-white/10`}
            >
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-white/60">{card.title}</p>
                  <p className="text-2xl font-semibold mt-2 text-white">
                    {card.value}
                  </p>
                </div>
                <div className="p-3 rounded-full bg-white/5">
                  {card.icon}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* 设备状态 */}
        <div className="mb-8">
          <Card
            title="设备状态"
            className="!bg-white/5 !border-white/10"
            styles={{
              header: { 
                borderBottom: '1px solid rgba(255,255,255,0.1)', 
                color: 'rgba(255,255,255,0.8)',
                background: 'transparent'
              },
              body: { 
                color: 'rgba(255,255,255,0.8)',
                background: 'transparent'
              }
            }}
          >
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {devices.map((device: Device) => (
                <div 
                  key={device.id} 
                  className="p-4 rounded-lg bg-white/5 border border-white/10"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-white/90">{device.name}</span>
                    {device.status === true ? (
                      <Tag color="success" className="border-0">
                        <Power className="w-4 h-4 inline-block mr-1" />
                        在线
                      </Tag>
                    ) : (
                      <Tag color="error" className="border-0">
                        <PowerOff className="w-4 h-4 inline-block mr-1" />
                        离线
                      </Tag>
                    )}
                  </div>
                  <div className="text-sm text-white/60">
                    {device.type && <div>类型: {device.type}</div>}
                    {device.data && (
                      <div className="mt-1">
                        {Object.entries(
                          typeof device.data === 'string' 
                            ? JSON.parse(device.data) 
                            : device.data
                        ).map(([key, value]) => (
                          <div key={key}>
                            {key === 'brightness' && '亮度: '}
                            {key === 'temperature' && '温度: '}
                            {key === 'volume' && '音量: '}
                            {key === 'locked' && '锁定: '}
                            {String(value)}
                            {key === 'brightness' && '%'}
                            {key === 'temperature' && '°C'}
                            {key === 'volume' && '%'}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* 最近执行的场景 */}
        <div className="mb-8">
          <Card
            title="最近执行的场景"
            className="!bg-white/5 !border-white/10"
            styles={{
              header: { 
                borderBottom: '1px solid rgba(255,255,255,0.1)', 
                color: 'rgba(255,255,255,0.8)',
                background: 'transparent'
              },
              body: { 
                color: 'rgba(255,255,255,0.8)',
                background: 'transparent'
              }
            }}
          >
            <div className="space-y-4">
              {recentExecutions.map((execution: SceneExecution) => (
                <div 
                  key={execution.id}
                  className="p-4 rounded-lg bg-white/5 border border-white/10 flex items-center justify-between"
                >
                  <div>
                    <div className="text-white/90">{execution.scene.name}</div>
                    <div className="text-sm text-white/60">
                      执行时间: {new Date(execution.executedAt).toLocaleString()}
                    </div>
                  </div>
                  <Tag 
                    color={execution.status === 'success' ? 'success' : 'error'}
                    className="border-0"
                  >
                    {execution.status === 'success' ? '执行成功' : '执行失败'}
                  </Tag>
                </div>
              ))}
              {recentExecutions.length === 0 && (
                <div className="text-center text-white/60 py-4">
                  暂无执行记录
                </div>
              )}
            </div>
          </Card>
        </div>
      </div>
    </DashboardLayout>
  )
} 